Page({
  data: {
    formData: {
      title: '',
      company: '',
      position: '',
      description: '',
      requirements: '',
      skills: '',
      status: 'open'
    },
    isFormValid: false,
    baseUrl: 'http://localhost:3000',
    userInfo: null // 添加用户信息字段
  },

  onLoad: function(options) {
    // 加载用户信息
    this.loadUserInfo();

    // 如果是编辑模式，加载现有数据
    if (options.id) {
      this.loadJobData(options.id);
    }
  },

  // 加载用户信息
  loadUserInfo: function() {
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({ userInfo });
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
    }
  },

  // 加载岗位数据（编辑模式）
  loadJobData: function(id) {
    wx.request({
      url: `${this.data.baseUrl}/api/jobs/${id}`,
      method: 'GET',
      success: (res) => {
        this.setData({
          formData: res.data,
          isFormValid: true
        });
      }
    });
  },

  // 处理输入
  handleInput: function(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value || e.detail.detail.value; // 兼容 input 和 radio
    
    this.setData({
      [`formData.${field}`]: value
    });
    
    this.validateForm();
  },

  // 表单验证
  validateForm: function() {
    const { title, company, position, description, requirements, skills } = this.data.formData;
    const isValid = title && company && position && description && requirements && skills;
    
    this.setData({
      isFormValid: isValid
    });
  },

  // 提交表单
  submitForm: function(e) {
    if (!this.data.isFormValid || !this.data.userInfo) {
      if (!this.data.userInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
      }
      return;
    }

    wx.showLoading({
      title: '发布中...'
    });

    const { formData, userInfo } = this.data;
    const postData = { ...formData, user_id: userInfo.id }; // 添加 user_id 到请求数据中

    wx.request({
      url: `${this.data.baseUrl}/api/jobs`,
      method: 'POST',
      data: postData,
      success: (res) => {
        wx.hideLoading();
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 2000
        });
        
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/jobs/jobs'
          });
        }, 2000);
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({
          title: '发布失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  }
});